import {
  Provide,
  Post,
  Body,
  Get,
  ALL,
  Validate,
  Inject,
  Query,
} from '@midwayjs/decorator';

import {
  CoolController,
  BaseController,
  CoolCommException,
} from '@cool-midway/core';
import { WeiboCommentsEntity } from '../../entity/blogComment';
import { CreateApiDoc } from '@midwayjs/swagger';
// import { AddCommentDTO } from '../../dto/weibo';
import { Context } from 'egg';
import { WeiboCommentsService } from '../../service/comment';
import { UserActionLogService } from '../../../user/service/log';
import { UserNotifyService } from '../../../user/service/notify';
import { WeiboBlogService } from '../../service/weibo';

/**
 * 描述
 */
@Provide()
@CoolController({
  api: [],
  entity: WeiboCommentsEntity,
  service: WeiboCommentsService,
})
export class WeiboCommentsController extends BaseController {
  @Inject()
  ctx: Context;

  @Inject()
  weiboComSrv: WeiboCommentsService;

  @Inject()
  userActionLogSrv: UserActionLogService;

  @Inject()
  userNotifySrv: UserNotifyService;

  @Inject()
  blogSrv: WeiboBlogService;

  @CreateApiDoc()
    .summary('评论与回复')
    .param('blogId', { required: true })
    .param('content', { required: true })
    .param('parentCommentId')
    .param('replyCommentId')
    .respond(200)
    .build()
  @Post('/reply')
  @Validate()
  async commentReply(@Body(ALL) query: any) {
    const userId = this.ctx.user.id;
    const data = await this.weiboComSrv.addComment({ ...query, userId });
    const blog = await this.blogSrv.info(query.blogId);

    // 存消息通知 不是自己的评论 不是自己回复自己 不是自己的博客 才通知
    if (
      userId != blog.userId &&
      data.parentCommentUserId != userId &&
      data.replyCommentUserId != userId
    ) {

      let pm = {
        type: 2, //1、公告 2、提醒 3、私信
        action: 2, // 1点赞 2评论 3回复 4关注
        targetId: data.blogId,
        userId: null,
        senderId: userId,
        commentId: null,
      };
      if (query.parentCommentId) {
        pm.userId = data.parentCommentUserId;
        pm.commentId = data.parentCommentId;
      } else if (query.replyCommentId) {
        pm.userId = data.replyCommentUserId;
        pm.commentId = data.replyCommentId;
      } else {
        pm.userId = blog.userId;
      }
      this.userNotifySrv.save(pm);
    }

    return this.ok(data);
  }

  @CreateApiDoc()
    .summary('评论列表')
    .param('blogId', { required: true })
    .param('parentCommentId')
    .param('page', { required: true })
    .param('size', { required: true })
    .param('order', { required: true })
    .respond(200)
    .build()
  @Get('/page')
  @Validate()
  async commentList(@Query(ALL) query: any) {
    const { blogId, parentCommentId } = query;
    if (!blogId) {
      throw new CoolCommException('博客不存在或已删除~');
    }
    let list: any[] = [];
    // 一级评论  else  二级评论
    if (!parentCommentId) {
      query.commentLevel = 1;
      list = await this.weiboComSrv.findCommentList(query);
      list = await this.checkIsLove(list, this.ctx.user?.id);
      if (list && list.length) {
        await Promise.all(
          list.map(async item => {
            const pm = {
              blogId: item.blog_id,
              commentLevel: 2,
              parentCommentId: item.id,
              order: query.order,
              size: 1,
              page: 1,
            };
            // item.ip_addr = await this.userActionLogSrv.getUserIpAddr(
            //   item.user_id
            // );
            item.replys = await this.weiboComSrv.findCommentList(pm);
            item.replys = await this.checkIsLove(
              item.replys,
              this.ctx.user?.id
            );
          })
        );
      }
    } else {
      query.commentLevel = 2;
      list = await this.weiboComSrv.findCommentList(query);
      if (this.ctx.user?.id) {
        list = await this.checkIsLove(list, this.ctx.user?.id);
      }
    }
    return this.ok(list);
  }

  /**
   * 判断当前评论是否点赞
   * @param list
   * @param userId
   * @returns
   */
  async checkIsLove(list: any[], userId: number) {
    if (list && list.length) {
      await Promise.all(
        list.map(async item => {
          if (userId) {
            item['is_love'] = await this.weiboComSrv.hasLove({
              blogId: item.blog_id,
              userId: userId,
              commentId: item.id,
            });
            // item.ip_addr = await this.userActionLogSrv.getUserIpAddr(
            //   item.user_id
            // );
          } else {
            item['is_love'] = false;
          }
          item['count_love']=await this.checkCountLove(item.blog_id,item.id)
        })
      );
    }
    return list;
  }
  /**
   * 查询当前评论的点赞数量
   * @param blogId
   * @param commnetId
   */
  async checkCountLove(blogId: number, commnetId: number) {
   return await this.weiboComSrv.findCommentLoveCount(blogId, commnetId);
  }

  @CreateApiDoc()
    .summary('评论点赞')
    .param('blogId', { description: 'blogId博客ID' })
    .param('commentId', { description: 'commentId评论ID' })
    .respond(200)
    .build()
  @Get('/love')
  async love(@Query() blogId: number, @Query() commentId: number) {
    const data = await this.weiboComSrv.love({
      blogId,
      commentId,
      userId: this.ctx.user.id,
    });
    const comment = await this.weiboComSrv.info(commentId);
    // 存消息通知
    if (this.ctx.user.id != comment.userId && data == 'up') {
      this.userNotifySrv.save({
        type: 2, //1、公告 2、提醒 3、私信
        action: 1, // 1点赞 2评论 3回复 4关注
        targetId: blogId,
        commentId:comment.id,
        senderId: this.ctx.user.id,
        userId: comment.userId,
      });
    }
    return this.ok(data);
  }
}
